package com.zd.file.common;

import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author master336@163.com
 */
public class FileUtils{
    static Logger logger = LoggerFactory.getLogger(FileUtils.class);
    private static HashMap<String,String> CONTENT_TYPE = new HashMap();
    private final static String SYS_CONFIG = "conf/mime-types.properties";
    static {
        Properties properties = new Properties();
        try {
            properties.load(FileUtils.class.getClassLoader().getResourceAsStream(SYS_CONFIG));
            for (Map.Entry<Object,Object> entry : properties.entrySet()) {
                CONTENT_TYPE.put((String) entry.getKey(),(String) entry.getValue());
            }

        } catch (IOException e) {
            logger.error("加载自定义content-type配置失败",e);
        }
    }
    /**
     * 根据文件名获取contentType
     * @param filename
     * @return
     */
    public static String getContentTypeByFile(File filename) {
        String contentType = new MimetypesFileTypeMap().getContentType(filename);
        if (StringUtils.isEmpty(contentType) || contentType.equals(ContentType.APPLICATION_OCTET_STREAM.toString())) {
            contentType = CONTENT_TYPE.get(filename.getName().substring(filename.getName().lastIndexOf(".")));
            if (StringUtils.isEmpty(contentType)){
                contentType = ContentType.APPLICATION_OCTET_STREAM.toString();
            }
        }
        return contentType;

    }
}
